__author__ = 'zoulida'
from functools import lru_cache

import pandas as pd

from tools.timeTools import daystrTodaystr, datetimeTodaystr, daystrTodaystrYear_Month_Day
import akshare as ak



@lru_cache()
def getCal_dates():#获取交易日历


    tool_trade_date_hist_sina_df = ak.tool_trade_date_hist_sina()
    #print(tool_trade_date_hist_sina_df)
    tool_trade_date_hist_sina_df['trade_date'] = tool_trade_date_hist_sina_df['trade_date'].apply(lambda x: datetimeTodaystr(x) )
    #daystrTodaystr()
    #print(cal_dates2)

    return tool_trade_date_hist_sina_df


def is_open_day(date= '20230816'):
    # print(cal_dates[cal_dates['calendarDate'] == date])
    cal_dates = getCal_dates()
    if date in cal_dates['trade_date'].values:
        return True
    return False

def getOpenDayNum(start = '20220101',end = '20230227'):
    char1 = '-'
    if char1 in end:
        end = daystrTodaystr(end)
    if char1 in start:
        start = daystrTodaystr(start)
    cal_dates = getCal_dates()
    rangedates = cal_dates.query('\'%s\' <= trade_date <= \'%s\''%(start,end))
    #isopendays = rangedates[rangedates['is_open'] == 1]
    #isopendays = rangedates.query('is_open = 1')
        #cal_dates[cal_dates['cal_date'] >= start and cal_dates['cal_date'] <= end]
    #print(isopendays)

    return len(rangedates)


def getLastOpenDay(date):
    cal_dates = getCal_dates()
    #cal_dates_shifted = cal_dates.shift(1)
    lastday = cal_dates[cal_dates['trade_date'] < date].iloc[-1, 0]

    return lastday

def getNextOpenDay(date):#输出20230227格式的，输入任意格式
    char1 = '-'
    if char1 in date:
        date = daystrTodaystr(date)
    cal_dates = getCal_dates()
    #cal_dates_shifted = cal_dates.shift(1)
    nextday = cal_dates[cal_dates['trade_date'] >= date].iloc[0, 0]
    return nextday

def getNextOpenDayContainHorizontalBar(date):#输出2023-02-27格式的，输入任意格式
    char1 = '-'
    if char1 in date:
        date = daystrTodaystr(date)
    cal_dates = getCal_dates()
    #cal_dates_shifted = cal_dates.shift(1)
    nextday = cal_dates[cal_dates['trade_date'] >= date].iloc[0, 0]
    return daystrTodaystrYear_Month_Day(nextday)

if __name__ == '__main__':
    #bl = is_open_day('20200308')
    bl = getNextOpenDay('20241207')
    #print(bl)
    num = getOpenDayNum(start = '2022-01-01',end = '2023-02-27')
    print(num)
    #spot()
    #getCal_dates()

    print(is_open_day())